package com.health.viewscontrols;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.health.MainActivity_Menu_JTYS;
import com.health.NovaActivity;
import com.health.NovaApplication;
import com.health.NovaApplication;
import com.health.R;
import com.health.adapter.DoctorAdapter;
import com.health.adapter.SSQAdapter;
import com.health.adapter.XZ_CZHospitalAdapter;
import com.health.model.UpDataReturn;
import com.health.tablebean.BD_DD_AREA;
import com.health.tablebean.BD_ORGANIZE_EMPLOYEE;
import com.health.tablebean.BD_ORGANIZE_INSTITUTION;
import com.health.tablebean.JTYSDoctorContInfoBean;
import com.health.tools.GetPostJTYS;
import com.health.tools.GlobalContsJTYS;
import com.health.tools.JX_FWXMB;
import com.health.tools.SPUtil;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import static com.novabluetooth.services.ktxyj.Constants.AREA_CODE;

/**
 * 登录界面
 */

public class LoginActivity extends NovaActivity implements OnItemSelectedListener, OnClickListener {

    private static final String TAG = "LoginActivity";
    private Spinner spinner_jd;
    private Spinner spinner_xz;
    private Spinner spinner_cz;
    private Spinner spinner_employee;
    private TextView tv_username;
    private String str_cs_ORGANCODE = AREA_CODE;// 城市编码
    private String str_xz_ORGANCODE = "";// 乡镇编码
    private String str_CZ_ORGANCODE = "";// 村庄编码
    private List<BD_ORGANIZE_INSTITUTION> listCS_Hospital = new ArrayList<BD_ORGANIZE_INSTITUTION>();// 城市医院
    private List<BD_ORGANIZE_INSTITUTION> listXZ_Hospital = new ArrayList<BD_ORGANIZE_INSTITUTION>();// 乡镇医院
    private List<BD_ORGANIZE_INSTITUTION> listCZ_Hospital = new ArrayList<BD_ORGANIZE_INSTITUTION>();// 村庄医院
    private String Detail_p = "370188";
    private String Detail_c = "";
    private String str_xz_name = "";// 乡镇name
    private String str_cz_name = "";// 村庄name
    private String str_jdr = "";// 建档人
    private String str_jdrno = "";// 建档人no
    private String str_jdpassward = "";// 建档人登录密码
    private String str_jdidcard = "";// 建档人身份证号
    private String str_jdrusername = "";// 建档人名字
    private List<BD_ORGANIZE_EMPLOYEE> listCZ_Employees = new ArrayList<BD_ORGANIZE_EMPLOYEE>();// 村庄医院
    private LinearLayout ll_exit;
    private Button bt_login;
    // private String str_jd = "";
    // private String str_jd_name = "";
    private List<BD_DD_AREA> listJD = new ArrayList<BD_DD_AREA>();// 街道
    private String Detail_jd = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        setContentView(R.layout.activity_login);
        findViews();
        setListeners();

        // getPro(3, "3701");
        getCS_XZ_Hospital(0, NovaApplication.getXzqhNo().substring(0, 4));
//		getCS_XZ_Hospital(0, "3701");

        // List<BD_ORGANIZE_INSTITUTION> bd_ORGANIZE_INSTITUTIONAs =
        // NovaApplication.fdbmanger
        // .findAllByWhere(BD_ORGANIZE_INSTITUTION.class, "PARENTID='" +
        // "370188B20005" + "'");
        // bindSpinner_CS_XZ_Hospital(0, bd_ORGANIZE_INSTITUTIONAs);
    }

    @Override
    public void findViews() {

        spinner_jd = (Spinner) findViewById(R.id.nicespinner_jd);
        spinner_xz = (Spinner) findViewById(R.id.spinner_xz);
        spinner_cz = (Spinner) findViewById(R.id.spinner_cz);
        spinner_employee = (Spinner) findViewById(R.id.spinner_employee);
        tv_username = (TextView) findViewById(R.id.tv_username);

        ll_exit = (LinearLayout) findViewById(R.id.ll_exit);
        bt_login = (Button) findViewById(R.id.bt_login);
    }

    @Override
    public void setListeners() {
        spinner_jd.setOnItemSelectedListener(this);
        spinner_cz.setOnItemSelectedListener(this);
        spinner_xz.setOnItemSelectedListener(this);
        spinner_employee.setOnItemSelectedListener(this);

        ll_exit.setOnClickListener(this);
        bt_login.setOnClickListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.nicespinner_jd:
                // str_jd = listJD.get(position).getGBCODE();
                // str_jd_name = listJD.get(position).getNAME();
                break;
            case R.id.spinner_xz:
                str_xz_ORGANCODE = listXZ_Hospital.get(position).getORGANCODE();
                str_xz_name = listXZ_Hospital.get(position).getORGANNAME();
                getCS_XZ_Hospital(2, str_xz_ORGANCODE);
                setDataTextView_Hospital();
                break;
            case R.id.spinner_cz:
                str_CZ_ORGANCODE = listCZ_Hospital.get(position).getORGANCODE();
                str_cz_name = listCZ_Hospital.get(position).getORGANNAME();
                setDataTextView_Hospital();
                break;
            case R.id.spinner_employee:
                str_jdr = listCZ_Employees.get(position).getNAME();
                str_jdrno = listCZ_Employees.get(position).getUSER_ID();
                str_jdpassward = listCZ_Employees.get(position).getPASSWORD();
                str_jdidcard = listCZ_Employees.get(position).getIDCARD();
                str_jdrusername = listCZ_Employees.get(position).getUSER_NAME();
                tv_username.setText("登录账号：" + str_jdrusername);
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    /**
     * 设置省市区编号
     *
     * @author 王婷婷
     * @date 2015年12月8日 下午4:19:34
     */
    private void setDataTextView_Hospital() {
        if (str_CZ_ORGANCODE.equals("")) {
            getCS_XZ_Employee(str_xz_ORGANCODE);
        } else {
            getCS_XZ_Employee(str_CZ_ORGANCODE);
        }
    }

    /**
     * 获取医生
     *
     * @param parentId
     * @author 王婷婷
     * @date 2015年12月9日 下午4:00:35
     */
    private void getCS_XZ_Employee(String parentId) {
        try {
            // List<BD_ORGANIZE_EMPLOYEE> bd_ORGANIZE_INSTITUTIONAs =
            // dbmanger.selectBD_ORGANIZE_EMPLOYEEbyORGANCODE(parentId);
            List<BD_ORGANIZE_EMPLOYEE> bd_ORGANIZE_INSTITUTIONAs = NovaApplication.fdbmanger
                    .findAllByWhere(BD_ORGANIZE_EMPLOYEE.class, "ORGANCODE='" + parentId + "'");

            int pLength = bd_ORGANIZE_INSTITUTIONAs.size();
            if (pLength > 0) {
                NovaApplication.setDoctorList(bd_ORGANIZE_INSTITUTIONAs);// 医生列表赋值
                bindSpinner_Doctors(bd_ORGANIZE_INSTITUTIONAs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 绑定医生
     *
     * @param bds
     * @author 王婷婷
     * @date 2015年12月9日 下午3:30:40
     */
    public void bindSpinner_Doctors(List<BD_ORGANIZE_EMPLOYEE> bds) {
        // 判断当前乡镇在数组中的位置并显示
        listCZ_Employees = bds;

        DoctorAdapter adapter_p = new DoctorAdapter(getApplicationContext(), listCZ_Employees);
        // adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_employee.setAdapter(adapter_p);
        spinner_employee.setOnItemSelectedListener(this);
    }

    /**
     * 获取城市乡镇医院 flag 0城市 1乡镇 2城市
     *
     * @param flag
     * @author 王婷婷
     * @date 2015年12月8日 上午11:55:03
     */
    private void getCS_XZ_Hospital(int flag, String parentId) {
        try {
            List<BD_ORGANIZE_INSTITUTION> bd_ORGANIZE_INSTITUTIONAs = NovaApplication.fdbmanger
                    .findAllByWhere(BD_ORGANIZE_INSTITUTION.class, "PARENTID='" + parentId + "'");
            int pLength = bd_ORGANIZE_INSTITUTIONAs.size();
            if (pLength == 0 && 0 == flag && !"3701".equals(parentId)) {
                getCS_XZ_Hospital(0, "3701");
                return;
            }
            if (pLength > 0) {
                if (flag == 0) {
                    listCS_Hospital = bd_ORGANIZE_INSTITUTIONAs;
                    str_cs_ORGANCODE = listCS_Hospital.get(0).getORGANCODE();
                    getCS_XZ_Hospital(1, str_cs_ORGANCODE);
                } else {
                    bindSpinner_CS_XZ_Hospital(flag, bd_ORGANIZE_INSTITUTIONAs);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void bindSpinner_CS_XZ_Hospital(int flag, List<BD_ORGANIZE_INSTITUTION> bds) {
        if (flag == 1) {
            // 判断当前乡镇在数组中的位置并显示
            listXZ_Hospital = bds;
            int flagIndex1 = -1;

            XZ_CZHospitalAdapter adapter_p = new XZ_CZHospitalAdapter(getApplicationContext(), listXZ_Hospital);
            // adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner_xz.setAdapter(adapter_p);
            if (flagIndex1 != -1) {
                spinner_xz.setSelection(flagIndex1);
            }
            spinner_xz.setOnItemSelectedListener(this);
        } else if (flag == 2) {
            // 判断当前城市在数组中的位置并显示
            listCZ_Hospital = bds;
            int flagIndex2 = -1;
            XZ_CZHospitalAdapter adapter = new XZ_CZHospitalAdapter(getApplicationContext(), listCZ_Hospital);
            spinner_cz.setAdapter(adapter);
            if (flagIndex2 != -1) {
                spinner_cz.setSelection(flagIndex2);
            }
            spinner_cz.setOnItemSelectedListener(this);
        }
    }

    /**
     * flag 1省 2市 3区/县 4乡镇 5 街道
     *
     * @param flag
     * @param dlevel
     * @author 王婷婷
     * @date 2015年12月8日 上午11:55:03
     */
    private void getPro(int flag, String dlevel) {
        try {
            int pLength = 0;
            // List<BD_DD_AREA> bd_DD_AREAs =
            // dbmanger.selectBD_DD_AREAbyDLEVEL(dlevel);
            List<BD_DD_AREA> bd_DD_AREAs = NovaApplication.fdbmanger.findAllByWhere(BD_DD_AREA.class,
                    "DLEVEL='" + dlevel + "'");
            if (null != bd_DD_AREAs) {
                pLength = bd_DD_AREAs.size();
            }
            if (pLength > 0) {
                bindSpinner(flag, bd_DD_AREAs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void bindSpinner(int flag, List<BD_DD_AREA> bds) {
        if (flag == 3) {
            // 判断当前城市在数组中的位置并显示
            listJD = bds;
            int flagIndex3 = -1;
            if (!Detail_jd.equals("")) {
                int length = listJD.size();
                for (int i = 0; i < length; i++) {
                    if (listJD.get(i).getGBCODE().equals(Detail_jd)) {
                        flagIndex3 = i;
                    }
                }
            }
            SSQAdapter adapter_jd = new SSQAdapter(getApplicationContext(), listJD);
            // adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner_jd.setAdapter(adapter_jd);
            if (flagIndex3 != -1) {
                spinner_jd.setSelection(flagIndex3);
                Detail_jd = "";
            }
            getCS_XZ_Hospital(0, AREA_CODE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_exit:
                finish();
                break;
            case R.id.bt_login:
                SharedPreferences sp = mContext.getSharedPreferences(SPUtil.SP_NAME, 0);
                sp.edit().putString(SPUtil.STR_JDDW, str_xz_name)
                        .putString(SPUtil.STR_CZNO, str_cz_name)
                        .putString(SPUtil.STR_JDRNO, str_jdrno)
                        .putString(SPUtil.STR_JDDWNO, str_xz_ORGANCODE)
                        .putString(SPUtil.STR_JDR, str_jdr)
                        .putString(SPUtil.STR_JDPADDWARD, str_jdpassward)
                        .putString(SPUtil.STR_JDRUSERNAME, str_jdrusername)
                        .putString(SPUtil.STR_JDRIDCARD, str_jdidcard)
                        .commit();

                startActivity(new Intent(mContext, MainActivity_Menu_JTYS.class));
                finish();
                break;

            default:
                break;
        }
    }

    private void login() {

        // if (str_CZ_ORGANCODE.equals("")) {
        // str_jddwno = str_xz_ORGANCODE;
        // str_jddw = str_xz_name;
        //
        // } else {
        // str_jddwno = str_CZ_ORGANCODE;
        // str_jddw = str_cz_name;
        // }
        // if (TextUtils.isEmpty(str_jdr) || TextUtils.isEmpty(str_jdrno)) {
        // showTextDialog("请选择机构及人员");
        // return;
        // }
        // Log.e("ttttttt444444444-------", str_jd_name + "\n" + str_jd + "\n" +
        // str_bsc_name + "\n" + str_bsc + "\n"
        // + str_jddw + "\n" + str_jddwno + "\n" + str_xzq.replace("-", ""));
        // // 保存选中信息
        // saveID(str_jd_name, str_jd, str_bsc_name, str_bsc, str_jddw,
        // str_jddwno, str_jdr, str_jdrno,
        // str_ssqno.replace("-", ""), str_xzq.replace("-", ""), str_jdpassward,
        // str_p, str_c, str_n,
        // str_jdrusername);
        getFWXMB();
    }

    /**
     * 获取服务项目包
     *
     * @author 王婷婷
     * @date 2017年6月7日 下午3:56:04
     */
    private void getFWXMB() {
        Log.e(TAG, "NovaApplication.getJgbh()" + NovaApplication.getJgbh());
        List<JTYSDoctorContInfoBean> listsize = NovaApplication.fdbmanger.findAllByWhere(JTYSDoctorContInfoBean.class,
                "officeId='" + NovaApplication.getJgbh() + "'");
        if (listsize.size() > 0) {
            // 如果数据>0，不进行下载操作
            Intent intent2 = new Intent(LoginActivity.this, MainActivity_Menu_JTYS.class);
            intent2.putExtra("from", "MainActivity_Login2");
            startActivity(intent2);
            return;
        }
        getFWXMData(NovaApplication.getJgbh());

    }

    /**
     * 获取服务条目data
     *
     * @author 王婷婷
     * @date 2017年5月31日 下午1:48:17
     */
    private void getFWXMData(String jgbh) {
        try {
            Log.w(TAG, "getFWXMData()" + jgbh);

            String url = GlobalContsJTYS.getUrlPost_JTYS() + GetPostJTYS.URL_JTYS_FWXM + "?type=1&officeId=" + jgbh;
            Log.w(TAG, url);
            FinalHttp fh = new FinalHttp();
            fh.post(url, new AjaxCallBack<Object>() {

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    // Toast.makeText(context, "数据校验失败", 0).show();
                    cancelProgressDialog();
                    Log.w(TAG, errorNo + "\n" + strMsg);
                    // showTextDialog("请在系统设置--数据下载中，下载服务项目包");
                    Intent intent2 = new Intent(LoginActivity.this, MainActivity_Menu_JTYS.class);
                    intent2.putExtra("from", "MainActivity_Login2");
                    intent2.putExtra(GlobalContsJTYS.CONFIG_ACTIVITY, GlobalContsJTYS.CONFIG1);
                    startActivity(intent2);
                }

                @Override
                public void onSuccess(Object t) {
                    super.onSuccess(t);
                    // Toast.makeText(context, "数据校验成功", 0).show();
                    cancelProgressDialog();
                    Log.w(TAG, t.toString());
                    UpDataReturn up = JX_FWXMB.jxFwxmbData(t.toString());
                    Intent intent2 = new Intent(LoginActivity.this, MainActivity_Menu_JTYS.class);
                    if (up != null) {
                        if (up.getSize() > 0) {

                        } else {
                            // showTextDialog("请先在后台维护服务项目包，然后在系统设置--数据下载中，下载服务项目包");
                            intent2.putExtra(GlobalContsJTYS.CONFIG_ACTIVITY, GlobalContsJTYS.CONFIG2);
                        }
                    } else {
                        // showTextDialog("请在系统设置--数据下载中，下载服务项目包");
                        intent2.putExtra(GlobalContsJTYS.CONFIG_ACTIVITY, GlobalContsJTYS.CONFIG1);
                    }
                    intent2.putExtra("from", "MainActivity_Login2");
                    startActivity(intent2);
                }

                @Override
                public void onLoading(long count, long current) {
                    super.onLoading(count, current);
                }

                @Override
                public void onStart() {
                    super.onStart();
                    showProgressDialog("正在登录中，请稍后。。。");
                }

            });
        } catch (Exception e) {
            e.printStackTrace();
            // showTextDialog("请在系统设置--数据下载中，下载服务项目包");
            Intent intent2 = new Intent(LoginActivity.this, MainActivity_Menu_JTYS.class);
            intent2.putExtra("from", "MainActivity_Login2");
            intent2.putExtra(GlobalContsJTYS.CONFIG_ACTIVITY, GlobalContsJTYS.CONFIG1);
            startActivity(intent2);
        }
    }

}
